Functions in Lua

Table of Contents

The basic definition of function uses the function keyword.

  function add(a, b)
     return a + b
  end

  print(add(10, 20))

1. Functions are First-Class Members

Anonymous functions. Functions are ordinary values, they can be placed in tables or passed to other functions.

  local multiply = function(a, b)
      return a * b
  end

  local operations = {
      op = multiply,
  }

  print(operations.op(2, 3)) -- => 6

Note, missing parameters receive nil by default. Extra arguments to an ordinary function are discarded.

2. Multiple Return Values

Lua functions can return several values. We can unpack the results

  local function values()
     return 1, 2, 3
  end

  local a, b, c = values() -- => a=1, b=2, c=3

2.1. Result Adjustment

Parentheses around function calls force only one result (first one)

  local a, b, c = (values())
  -- => a=1, b=nil, c=nil

3. Variadic Functions

A variadic function accepts extra arguments through ..., and we can convert arguments into a table when necessary.

  -- basic usage
  local function show_all(...)
     print(...)
  end

  show_all("Lua", 5.5, true)

  -- Converting to table
  local function sum(...)
     local values = table.pack(...)
     local total = 0

     for i = 1, values.n do
        total = total + values[i]
     end

     return total
  end

  print(sum(10, 20, 30))

In Lua 5.5, we can directly give the extra arguments a name in parameters declaration.

  local function sum(... values)
     -- same here
  end

Similarly, values.n tells the number of arguments.

Date: 2026-07-24 Fri